import React from 'react'
import App from 'next/app'
import HeaderDom from '@components/global/head-dom'
import TabBarLyout from '@components/layout/tabBar/index'
import { Provider } from 'react-redux'
import withRedux from '../store/with-redux'
import { StorePropsInterface } from '../store/types'
import '../styles/global.scss'
import '../router/hook'
import { sessionLoginAction as Oauth_sessionLoginAction  } from '@store/oauth/actions'
import { sessionLoginAction as Admin_sessionLoginAction } from '@store/auth/actions'
import Cookie from 'js-cookie'
import { PublicENV, isDev, isServer } from '@config/env'
import { Modal } from 'antd-mobile';

const alert = Modal.alert;

class MyApp extends App<StorePropsInterface> {

  static async getInitialProps(data: any) {
    if (isServer) {
      console.log('MyApp - getInitialProps')
      await Promise.all([
        data.reduxStore.dispatch(Oauth_sessionLoginAction(data)),
        data.reduxStore.dispatch(Admin_sessionLoginAction(data))
      ])
    }
    const { Component } = data
    let pageProps = {}
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(data)
    }
    return { pageProps }
  }

  componentDidMount() {
    const { oauth, auth } = this.props.reduxStore.getState()
    // 如果判断没有登录第三方就清除 cookie, 避免下次进来重新请求用户数据
    if (!oauth.name) {
      Cookie.remove(PublicENV.OAUTH_LOGIN)
    }
    if (!auth.user) {
      Cookie.remove(PublicENV.ADMIN_LOGIN)
    }
    if (!isDev) {
      alert('友情提示！', '目前移动端Next版本正在开发中，如想看移动端完整内容，请转Vue版本', [
        { text: '取消' },
        {
          text: '确定', onPress: () => {
            location.href = 'https://wangyabin.top/proxy-api/web/m.html'
          }
        },
      ]);
    }
  }

  /**
   * 获取布局
   */
  getLayout() {
    const { Component, pageProps } = this.props
    const { layout = {} } = pageProps
    switch (layout.type) {
      case 'tabBar':
        return (
          <TabBarLyout tabBar={layout.tabBar}>
            <Component {...pageProps} />
          </TabBarLyout>
        )
      default:
        return (
          <Component {...pageProps} />
        )
    }
  }

  render() {
    const { pageProps, reduxStore } = this.props
    const { title } = pageProps

    return (
      <Provider store={reduxStore}>
        <HeaderDom title={title} />
        {
          this.getLayout()
        }
      </Provider>
    )
  }
}

export default withRedux(MyApp)